import {page, pageFunc} from "../common/PageBuilder";
import {BasePage, BasePageData} from "../common/core/BasePage";
import {waitForDataLoad} from "../../modules/coreModule/managers/DataManager";
import {Exam, examRepo} from "../../modules/examModule/data/Exam";
import {ExamInterface} from "../../modules/examModule/ExamCommon";
import {pageMgr} from "../../modules/coreModule/managers/PageManager";
import {ExamRulePage} from "../examRule/ExamRulePage";
import {field} from "../../modules/coreModule/data/DataLoader";
import {PaymentPage} from "../payment/PaymentPage";
import {QuestionPage} from "../question/QuestionPage";
import {handleError} from "../../modules/coreModule/managers/AlertManager";
import {AuthPage, UserPage} from "../common/partPages/UserPage";

class Data extends BasePageData {

	@field([Exam])
	exams: Exam[] = [];
	@field(Number)
	selectedIdx: number = 0;
}

@page("levelChoice", "等级选择")
export class LevelChoicePage extends BasePage<Data> {

	public data = new Data();

	/**
	 * 部分页
	 */
	public userPage: UserPage = new UserPage();

	/**
	 * 处理顶部栏以下的高度
	 */
	onLoad(e) {
		super.onLoad(e);
		this.loadData().then();
	}

	@waitForDataLoad
	private loadData() {
		return this.setData({exams: examRepo().find()})
	}

	// region 事件

	/**
	 * 当用户进行选择考试难度时的回调函数
	 */
	@pageFunc
	public onExamChange(event) {
		this.setData({selectedIdx: event.detail});
	}

	/**
	 * 点击开始考试
	 */
	@pageFunc
	@handleError
	public async startExam() {
		const exam = this.data.exams[this.data.selectedIdx];
		const curLevel = this.userPage.userInfo.certification.level;
		if (exam.level.level > curLevel.level + 1)
			throw "请勿越级考核！";
		if (exam.level.level <= curLevel.level)
			throw "无需重复考核！";

		const res = await ExamInterface.StartExam({examId: exam._id})
		const questionIds = res.questionIds;
		const examRecordId = res.examRecordId;

		if (res.trade && res.trade.price != 0)
			await pageMgr().change(PaymentPage, <any>{
				tradeId: res.trade._id, onSuccess: () =>
					pageMgr().change(QuestionPage, {
						examId: exam._id, questionIds, examRecordId
					})
			})
		else
			await pageMgr().change(QuestionPage, {
				examId: exam._id, questionIds, examRecordId
			})

		// await pageMgr().change(QuestionPage, {
		// 	examId: exam._id, questionIds, examRecordId
		// })
	}

	/**
	 * 点击查看考试规则
	 */
	@pageFunc
	public toExamRule() {
		pageMgr().change(ExamRulePage)
	}

	// endregion

}
